package cn.edu.qfnu.oj.service.impl;

import cn.edu.qfnu.common.dao.BaseDao;
import cn.edu.qfnu.common.service.Impl.BaseServiceImpl;
import cn.edu.qfnu.common.utils.TimeUtils;
import cn.edu.qfnu.oj.entity.LoginLog;
import cn.edu.qfnu.oj.service.LoginLogService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * OnlineJudge of QF_NU
 * Created by LS on 2017/7/18.
 */
@Service("loginLogService")
public class LoginLogServiceImpl extends BaseServiceImpl<LoginLog, Integer> implements LoginLogService {


    public String getIpAddress(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (inetAddress != null) {
                    ipAddress= inetAddress.getHostAddress();
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length() > 15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    @Override
    public void saveLog(HttpServletRequest request, String...args) {
        /*
         * username:0
         * ip:1
         * result:2
         */
        LoginLog loginLog =
                new LoginLog(TimeUtils.getLocalTime(), args[0], getIpAddress(request), args[1]);
        save(loginLog);
    }
}
